package com.xl.web.service.zoom;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.xl.base.annotation.DataSource;
import com.xl.base.interceptor.ExceptionInterceptor;
import com.xl.base.page.Page;
import com.xl.base.page.PageBean;
import com.xl.core.enums.SourceEnum;
import com.xl.core.util.zoom.ZoomRestAPI;
import com.xl.core.util.zoom.model.ZoomUser;
import com.xl.web.dao.zoom.AccountDao;
import com.xl.web.entity.zoom.ZoomAccount;

@Service(value = "accountService")
public class AccountService<T extends ZoomAccount> {
	Logger log = Logger
			.getLogger(AccountService.class);
	@Resource
	private AccountDao<ZoomAccount> accountDao;

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	@SuppressWarnings({ "rawtypes", "unchecked" })
	/**
	 * 带分页面查询
	 * @param zoomAccount
	 * @param page
	 * @return
	 */
	public PageBean<T> queryPageAccountInfo(ZoomAccount zoomAccount, Page page)
			throws Exception {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<Map> accounts = accountDao.queryAccountInfo(zoomAccount);
		PageBean pageBean = new PageBean(accounts);
		return pageBean;
	}

	/**
	 * 非分页面查询
	 * 
	 * @param zoomAccount
	 * @return
	 */
	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public List<Map> queryAccountInfo(ZoomAccount zoomAccount) throws Exception {
		List<Map> accounts = accountDao.queryAccountInfo(zoomAccount);
		return accounts;
	}
	public ZoomAccount saveAccount(ZoomAccount zoomAccount) throws Exception {
		// 调用api添加用户账号
		// 调用api用到的model
		ZoomUser zoomUser = new ZoomUser();
		zoomUser.setType(zoomAccount.getType());
		zoomUser.setEmail(zoomAccount.getZoomAccount());
		zoomUser.setPassword(zoomAccount.getZoomPwd());
		zoomUser.setMeeting_capacity(zoomAccount.getCapacity());
		zoomUser.setDept(zoomAccount.getDept());
		// 根据公司获取密钥信息
		//ZoomRestAPI.setApiKeySecret(zoomAccount.getCompanyId());
		//zoomUser = ZoomRestAPI.createUser(zoomUser);
		if (zoomUser.getError().getCode() != null) {
		    log.debug(zoomUser.getError().getMessage());
			return  null;
		} else {
			// 添加成功
			zoomUser = ZoomRestAPI.getByZoomUserId(zoomUser.getId());
			zoomAccount.setHostId(zoomUser.getId());
			zoomAccount.setToken(zoomUser.getToken());
			zoomAccount.setPmi(zoomUser.getPmi());
			zoomAccount.setCapacity(zoomUser.getMeeting_capacity());
			zoomAccount.setType(zoomUser.getType());
			// 入库保存数据
			try {
				// 添加数据库异常时需要回退zoom账号
				accountDao.saveAccount(zoomAccount);
			} catch (Exception e) {
				ZoomRestAPI.deleteUser(zoomUser.getId(), zoomUser.getEmail());
				return null;
			}

		}
		return zoomAccount;
	}

	// 将该账号做逻辑删除
	public void delAccount(ZoomAccount zoomAccount) throws Exception {
		accountDao.delAccount(zoomAccount);
	}

	// 更新账号信息
	public void editAccount(ZoomAccount zoomAccount) throws Exception {
		accountDao.editAccount(zoomAccount);
	}

}
